<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/resource/css/bootstrap-table.min.css" type="text/css">

<!-- Latest compiled and minified JavaScript -->
<script src="/resource/js/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="/resource/js/bootstrap-table-zh-CN.min.js"></script>


<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js"></script>


<div id="toolbar">
  <div class="btn-group ml-3" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-info " onclick="AE()">添加</button>
    <button type="button" class="btn btn-primary " onclick="CopyNode()">复制</button>
    <button type="button" class="btn btn-success " onclick="DisplayModal('CoverPlan')">批量分配订阅</button>
    <button type="button" class="btn btn-warning " onclick="DisplayModal('CoverRoute')">批量分配路由</button>
    <button type="button" class="btn btn-danger " onclick="Del()">删除</button>
  </div>
</div>
<div class="modal fade bd-example-modal-lg" id="AEModal" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="AEModalLongTitle">编辑</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="AEForm">
          <input name="id" id="aeid" type="hidden">
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>名字</label>
                <input name="name" placeholder="名字" type="text" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>显示状态</label>
                <div>
                  <div class="custom-control custom-radio ">
                    <input name="show" class="custom-control-input" id="customRadioShow" type="radio" checked=""
                      value="1">
                    <label class="custom-control-label" for="customRadioShow">显示</label>
                  </div>
                  <div class="custom-control custom-radio ">
                    <input name="show" class="custom-control-input" id="customRadioNoShow" type="radio" value="-1">
                    <label class="custom-control-label" for="customRadioNoShow">隐藏</label>
                  </div>
                </div>

              </div>
            </div>
          </div>

          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>地址</label>
                <input name="host" placeholder="地址" type="text" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>端口</label>
                <input name="port" placeholder="端口" type="number" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>倍率</label>
                <input name="rate" placeholder="倍率" type="number" class="form-control" value="1">
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>协议</label>
                <select name="agreement" class="form-control" data-style="btn-primary">
                  <option value="v2ray/vmess">v2ray/vmess</option>
                  <option value="v2ray/vless">v2ray/vless</option>
                  <option value="shadowsocks/ss2022">shadowsocks/ss2022</option>
                  <option value="trojan/trojan">trojan/trojan</option>
                </select>
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label>顺序</label>
                <input name="order_id" placeholder="顺序" type="number" class="form-control">
              </div>
            </div>

          </div>
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>指定订阅</label>
                <select name="plan_id" id="limit_plan_id" class="form-control" data-style="btn-primary"
                  multiple="multiple" data-none-selected-text="请选择">

                </select>
              </div>
            </div>

            <div class="col">
              <div class="position-relative form-group">
                <label>指定路由</label>
                <select name="route_id" id="limit_route_id" class="form-control" data-style="btn-primary"
                  multiple="multiple" data-none-selected-text="请选择">

                </select>
              </div>
            </div>
          </div>

          <div class="position-relative form-group">
            <label>数据</label>
            <textarea name="service_json" class="form-control" rows="10"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="AEajax()">保存</button>
      </div>
    </div>
  </div>
</div>

<div class="modal fade bd-example-modal-lg" id="CoverPlan" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="CoverPlanLongTitle">批量分配订阅</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="AEForm">
          <input name="id" id="aeid" type="hidden">
          <p>选中的节点会被重新设置订阅！</p>
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>指定订阅</label>
                <select name="plan_id" id="limit_plan_id2" class="form-control" data-style="btn-primary"
                  multiple="multiple" data-none-selected-text="请选择">

                </select>
              </div>
            </div>
          </div>
          <div style="height: 200px;"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="BatchPlanAjax()">保存</button>
      </div>
    </div>
  </div>
</div>


<div class="modal fade bd-example-modal-lg" id="CoverRoute" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="CoverRouteLongTitle">批量分配路由</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="AEForm">
          <input name="id" id="aeid" type="hidden">
          <p>选中的节点会被重新设置路由！</p>
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>指定路由</label>
                <select name="route_id" id="limit_route_id2" class="form-control" data-style="btn-primary"
                  multiple="multiple" data-none-selected-text="请选择">
                </select>
              </div>
            </div>
          </div>
          <div style="height: 200px;"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="BatchRouteAjax()">保存</button>
      </div>
    </div>
  </div>
</div>

<script>
  let planData;
  let onlineUserCountAndLastPushAt;
  let hasInit = false;
  const $table = $('#table')
  $.fn.selectpicker.Constructor.BootstrapVersion = '4';
  $(function () {
    GetOnlineUserCountAndLastPushAt()

    getShowPlan()
    getServerRoute()

  })

  //获取订阅列表
  function getShowPlan() {
    $.ajax({
      type: "POST",
      url: "/{{.setting.admin_path}}/plan/get_rtm1",
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          planData = data.data.data
          for (let index = 0; index < data.data.data.length; index++) {
            const element = data.data.data[index];
            $("select[name='plan_id']").append(`<option value="${element.id}">${element.name}</option>`)
          }
          $('#limit_plan_id').selectpicker();
          $('#limit_plan_id2').selectpicker();
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数

      }
    });
  }

  //获取路由列表
  function getServerRoute() {
    $.ajax({
      type: "POST",
      url: "/{{.setting.admin_path}}/service_route/all",
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          planData = data.data.data
          for (let index = 0; index < data.data.data.length; index++) {
            const element = data.data.data[index];
            $("select[name='route_id']").append(`<option value="${element.id}">${element.remarks}</option>`)
          }
          $('#limit_route_id').selectpicker();
          $('#limit_route_id2').selectpicker();

        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数

      }
    });
  }

  //搜索
  function search() {
    $("#table").bootstrapTable('refresh', { pageNumber: 1 });
  }
  //清除搜索
  function cleanSearch() {
    $("select[data-function='search']").each(function (i, domEle) {
      // 选择第一个选项
      $(this).val($(this).find('option:first').val());
    })
    $("input[data-function='search']").each(function (i, domEle) {
      $(domEle).val("")
    })
    $("#table").bootstrapTable('refresh');
  }

  //AE表单
  function AE(data) {
    $('#AEForm')[0].reset();
    if (data != null) {
      $("#AEModalLongTitle").text("编辑")
      $("#AEForm input[type='hidden'],#AEForm input[type='number'],#AEForm input[type='text'],#AEForm select,#AEForm textarea").each(function (i, v) {

        for (let key in data.service) {
          if (key == $(v).attr("name")) {
            $(v).val(data.service[key])
          }
        }
      })

      $("#AEForm input[type='checkbox']").each(function (i, v) {
        for (let key in data.service) {
          if (key == $(v).attr("name")) {
            if (data.service[key] == 1) {
              $(v).attr("checked", "true")
            } else {
              $(v).removeAttr("checked")
            }
          }
        }
      })

      //单选默认值
      $("#AEForm input[type='radio']").each(function (i, v) {
        for (let key in data.service) {
          if (key == $(v).attr("name")) {
            $("#AEForm input:radio[name='" + key + "'][value='" + data.service[key] + "']").prop("checked", true)
          }
        }
      })


      $("#limit_plan_id").selectpicker('val', data.plan.map(plan => plan.id + ""));
      $("#limit_route_id").selectpicker('val', data.route.map(route => route.id + ""));


    } else {
      $("#limit_plan_id").selectpicker('val', '');
      $("#limit_route_id").selectpicker('val', '');

      $("#AEModalLongTitle").text("添加")
      $("#aeid").val("")

    }
    $('#AEModal').modal('show')
  }

  //ae提交
  function AEajax() {
    let d = {}
    let t = $("#AEForm").serializeArray();
    let planIds = []
    $.each(t, function () {
      d[this.name] = this.value;
    });

    d['plan_id'] = $("#limit_plan_id").selectpicker('val')
    d['route_id'] = $("#limit_route_id").selectpicker('val')

    if (d.agreement.split("/").length < 2) {
      notify('danger', '协议填写错误，请查看文档')
      return
    }

    $.ajax({
      type: "POST",
      url: "/{{.setting.admin_path}}/service/ae",
      data: d,
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "保存成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $('#AEModal').modal('hide')
        $("#table").bootstrapTable('refresh');
      }
    });
  }

  //删除数据
  function Del() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function (v, i) {
      ids.push(v.service.id)
    })

    $.ajax({
      type: "post",
      url: "/{{.setting.admin_path}}/service/del",
      data: { 'ids': ids },
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "删除成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $("#table").bootstrapTable('refresh');
      }
    });

  }

  //显示模态框
  function DisplayModal(htmlId) {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择节点！')
      return
    }
    $('#'+htmlId).modal('show')
    $("#limit_plan_id2").selectpicker('val', '');
    $("#limit_route_id2").selectpicker('val', '');
  }

  //复制节点
  function CopyNode(htmlId) {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length != 1) {
      notify('danger', '请选择一个节点！')
      return
    }
    console.log(delData)
    let d = delData[0].service
    console.log(d)
    delete d.id
    delete d.updated_at
    delete d.created_at
    
    $.ajax({
      type: "POST",
      url: "/{{.setting.admin_path}}/service/ae",
      data: d,
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "复制成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $("#table").bootstrapTable('refresh');
      }
    });

  }

  //批量分配订阅数据提交
  function BatchPlanAjax() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function (v, i) {
      ids.push(v.service.id)
    })

    $.ajax({
      type: "post",
      url: "/{{.setting.admin_path}}/service/batch_plan",
      data: { 'ids': ids, 'plan_id' : $("#limit_plan_id2").selectpicker('val')},
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "设置成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $('#CoverPlan').modal('hide')
        $("#table").bootstrapTable('refresh');
      }
    });
    
  }

  //批量分配路由数据提交
  function BatchRouteAjax() {
    let delData = $table.bootstrapTable('getSelections')
    if (delData.length == 0) {
      notify('danger', '请选择！')
      return
    }
    let ids = []
    delData.forEach(function (v, i) {
      ids.push(v.service.id)
    })

    $.ajax({
      type: "post",
      url: "/{{.setting.admin_path}}/service/batch_route",
      data: { 'ids': ids, 'route_id' : $("#limit_route_id2").selectpicker('val')},
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "设置成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $('#CoverRoute').modal('hide')
        $("#table").bootstrapTable('refresh');
      }
    });
    
  }




  //初始化表格
  function initTable() {

    $table.bootstrapTable({
      columns: [
        [
          {

          }, {
            title: '<input type="text"  placeholder="ID" class="form-control" name="id" data-function="search" data-type="eq"  />',
          }, {
            title: '<input type="text"  placeholder="协议" class="form-control" name="agreement" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="数据" class="form-control" name="service_json" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="名称" class="form-control" name="name" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="地址" class="form-control" name="host" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="端口" class="form-control" name="port" data-function="search" data-type="like" />',
          }, {
            title: '',
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="plan_id" id="so_plan_id_select_id">
                      <option selected value="0">全部</option>
                    </select>
                  </div>
          `,
          }, {
            title: `
                  <div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="show">
                      <option selected value="0">全部</option>
                      <option value="1">显示</option>
                      <option value="-1">隐藏</option>
                    </select>
                  </div>
          `,
          }, {
          }, {
            title: ``,
          }, {
          }, {
            title: `

                  <div class="input-group">
                    <button type="button" class="btn btn-twitter btn-icon-only" onclick="search()">
                      <span class="btn-inner--icon"><i class="fas fa-search"></i></span>
                    </button>
                    <button type="button" class="btn btn-google-plus btn-icon-only" onclick="cleanSearch()">
                      <span class="btn-inner--icon"><i class="fas fa-trash"></i></span>
                    </button>
                  </div>
          `,
          },
        ], [
          {
            checkbox: true,
          }, {
            field: 'service.id',
            sortName: 'id',
            title: 'ID',
            width: 80,
          }, {
            field: 'service.agreement',
            sortName: 'agreement',
            title: '协议',

          }, {
            field: 'service.service_json',
            sortName: 'service_json',
            title: '数据',
            visible: false,//隐藏
          }, {
            field: 'service.name',
            sortName: 'name',
            title: '名称',
          }, {
            field: 'service.host',
            sortName: 'host',
            title: '地址',
          }, {
            field: 'service.port',
            sortName: 'port',
            title: '端口',
          }, {
            field: 'service.rate',
            sortName: 'rate',
            title: '倍率',
          }, {
            field: 'plan.name',
            sortName: 'plan_id',
            title: '订阅组',
            formatter: function (value, row, index) {
              // let s = ""
              // row.plan.forEach(e => {
              //   s = s + e.name + "；"
              // });
              // return s

              return row.plan.length + " 个"

            }
          }, {
            field: 'service.show',
            sortName: 'show',
            title: '是否显示',
            formatter: function (value, row, index) {
              if (row.service.show == 1) {
                return `显示`
              }
              return `隐藏`;
            }
          }, {
            title: '在线和状态',
            formatter: function (value, row, index) {
              if (onlineUserCountAndLastPushAt[row.service.id] == undefined) {
                return `<span class="badge badge-dot">
                        <i class="bg-warning"></i>
                        <span class="status">离线</span>
                      </span>`
              } else {
                let htmlStr = (onlineUserCountAndLastPushAt[row.service.id][1] || 0) + " | ";

                if ((Math.floor(new Date().getTime() / 1000) - onlineUserCountAndLastPushAt[row.service.id][2]) < 300) {
                  htmlStr = htmlStr + `<span class="badge badge-dot">
                        <i class="bg-success"></i>
                        <span class="status">正常</span>
                      </span>`
                } else {
                  htmlStr = htmlStr + `<span class="badge badge-dot">
                        <i class="bg-dark"></i>
                        <span class="status">异常</span>
                      </span>`
                }
                return htmlStr


              }

            }
          }, {
            field: 'service.order_id',
            sortName: 'order_id',
            title: '顺序',
          }, {
            field: 'service.created_at',
            sortName: 'created_at',
            title: '创建时间',
            visible: false,//隐藏
          }, {
            field: 'operate',
            title: '操作',
            width: 120,
            events: {
              'click #edit': function (e, value, row, index) {
                AE(row)
              },
            },
            formatter: function (value, row, index) {
              return `
              <div class="btn-group" role="group" aria-label="Basic example">
                <button id="edit" type="button" class="btn btn-twitter btn-icon-only"><span class="btn-inner--icon"><i class="fas fa-edit"></i></span></button>
              </div>`;
            }
          }
        ]
      ], //列
      url: '/{{.setting.admin_path}}/service',
      method: 'post', //请求方法
      dataType: 'json',//数据格式
      toolbar: '#toolbar',
      pagination: true, //是否显示页码
      sidePagination: "server",//服务器处理分页
      serverSort: "true",//是否服务器处理排序
      sortName: 'order_id',
      sortOrder: 'desc',
      showRefresh: true,  //显示刷新按钮
      showColumns: true, //是否显示列下拉列表按钮
      showFullscreen: true, //是否显示全屏按钮
      responseHandler: function (res) {  //response数据处理
        return {
          "rows": res.data.data,
          "total": res.data.totle,
        };
      },

      //搜索
      queryParams: function (x) {

        $("select[data-function='search']").each(function (i, domEle) {
          x[$(domEle).attr("name")] = domEle.value
        })

        $("input[data-function='search']").each(function (i, domEle) {
          const bindingDomID = $(domEle).attr("data-select-binding")
          if (bindingDomID != undefined) {
            x[$(bindingDomID).attr("name")] = $(bindingDomID).val()
          }
          x[$(domEle).attr("name")] = domEle.value
        })

        GetOnlineUserCountAndLastPushAt()

        return x
      },
      onColumnSwitch: function (field, checked) { //列选择事件
        window.localStorage.setItem('service_hidden_columns', JSON.stringify($("#table").bootstrapTable('getHiddenColumns').map(function (it) { return it.field })))

      },
      onPostBody: function (data) {//渲染并在 DOM 中可用后触发

        if (hasInit == false && window.localStorage.getItem('service_hidden_columns') != null) {
          JSON.parse(window.localStorage.getItem('service_hidden_columns')).forEach(v => {
            $("#table").bootstrapTable('hideColumn', v);
          });
        }
        if (!hasInit) hasInit = true
      },

    })
  }

  //获取所有服务器当前在线用户数量和服务器最后提交时间
  function GetOnlineUserCountAndLastPushAt() {
    $.ajax({
      async: false,
      type: "POST",
      url: "/{{.setting.admin_path}}/service/online_user_count_and_last_push_at",
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          onlineUserCountAndLastPushAt = data.data.data
          initTable()
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数

      }
    });
  }


  document.addEventListener('keyup', function (event) {
    if (event.keyCode === 13) {
      // 回车键按下后的操作
      search()
    }
  });


</script>